<?php

declare(strict_types=1);

// 账号登录
namespace app\net2023dev\controller;

class Login
{
    public function index()
    {
        // 请求方式验证
        if (!request()->isPost()) {
            $apidb = [
                'code' => 201, //状态码
                'msg' => "请求有误-不是Post方式!", //状态信息
            ];
            return json($apidb);
        }
        
        $branch = request()->param('branch', '', 'trim');
        $uid = request()->param('uid', '', 'trim');
        $pw = request()->param('pw', '', 'trim');
        //验证规则
        $requestdb = [
            'branch' => $branch,
            'uid' => $uid,
            'pw' => $pw,
        ];
        $validate = new \app\net2023dev\validate\Login; //验证规则
        if (!$validate->check($requestdb)) {
            // 验证不过关提示
            $apidb = [
                'code' => 201, //状态码
                'msg' => "请求有误-" . $validate->getError(),
                'requestdb' => $requestdb,
                'validate' => $validate->getError(),
            ];
            return json($apidb);
        }
        $sqldb = \app\net2023dev\model\Login::field([
            // 'id',
            'uid', //用户编号
            // 'status', //帐号状态:0=禁用,1=启用
            // 'user_type', //帐号类型admin总部agent代理user一般用户
            'token',

        ])->where([
            'branch_dbid' => $branch,
            'uid' => $uid,
            'pw' => md5($pw)
        ])->find();
        if ($sqldb) {
            // 查到，登录成功
            $sqldb["token"] = md5($sqldb["token"] . 'md5(token)');
            cache('userdb_' . $sqldb["token"], $sqldb, 0);
            $apidb = [
                'code' => 200, //状态码
                'msg' => "登录成功", //状态信息
                'data' => $sqldb, //SQL数据
                '_cache' => cache('userdb_' . $sqldb["token"]),
            ];
            return json($apidb);
        } else {
            $apidb = [
                'code' => 201, //状态码
                'msg' => "登录失败", //状态信息
                'data' => $sqldb, //SQL数据

            ];
            return json($apidb);
        }
    }
    // 退出登录
    public function logout()
    {
        if (cache('userdb_' . request()->header('token'))) {
            cache('userdb_' . request()->header('token'), null);
            $apidb = [
                'code' => 200, //状态码
                'msg' => "退出登录成功：" . com_pathinfo(), //状态信息
                '_cache' => cache('userdb_' . request()->header('token')),
            ];
        } else {
            $apidb = [
                'code' => 201, //状态码
                'msg' => "退出登录失败：" . com_pathinfo(), //状态信息
                '_cache' => cache('userdb_' . request()->header('token')),
            ];
        }
        return json($apidb);
    }
}
